#include "level.h"

Level::Level()
{
	this->data = NULL;
}

Level::Level(short w, short h, short d)
{
	this->data = new char[w*h*d];
}

Level::~Level() 
{
	delete [] this->data;
}

void Level::blank(short w, short h, short d)
{
	this->data = new char[w*h*d];
	this->w = w;
	this->h = h;
	this->d = d;
	for (int x = 0; x < this->w; x++)
		for (int y = 0; y < this->h; y++)
			for (int z = 0; z < this->d; z++) 
				this->data[x + (y * this->d + z ) * this->w] = (y <= (this->h/2)-7) ? 1 : (y <= this->h/2-2) ? 3 : (y == (this->h/2)-1) ? 2 : 0;
				//this->data[x + (y * this->d + z ) * this->w] = 1;
}

int Level::load(const char* name) 
{
	gzFile gfile = gzopen(name, "rb");
	if (gfile == NULL) return 1;
	else {
		gzread(gfile, &this->w, 2);
		gzread(gfile, &this->h, 2);
		gzread(gfile, &this->d, 2);
		this->data = new char[w*h*d];
		gzread(gfile, this->data, w*h*d);
		gzclose(gfile);
	}
	return 0;
}

void Level::save(const char* name)
{
	gzFile gfile = gzopen(name, "wb");
	gzwrite(gfile, &this->w, 2);
	gzwrite(gfile, &this->h, 2);
	gzwrite(gfile, &this->d, 2);
	gzwrite(gfile, this->data, w*h*d);
	gzclose(gfile);
}

int Level::dump(char* heap)
{
	if (this->data != NULL) {
		memcpy(heap, this->data, w*d*h);
		return 0;
	} else
		return 1;
}

int Level::operator()(short x, short y, short z, char type)
{
	if (x > -1 && y > -1 && z > -1 && x < this->w && y < this->h && z < this->d) {
		this->data[x + ((y*this->d +z ) * this->w)] = type;
		return 0;
	} else 
		return 1;
}

char Level::operator()(short x, short y, short z)
{
	if (x > -1 && y > -1 && z > -1 && x < this->w && y < this->h && z < this->d)
		return this->data[x + ((y*this->d +z ) * this->w)];
	else 
		return -1;
}

short Level::WIDTH()
{
	return this->w;
}

short Level::HEIGHT()
{
	return this->h;
}

short Level::DEPTH()
{
	return this->d;
}
